/*=============================================================
 * 		General
 =============================================================*/

function showMessage(message) {
	$('#main_container').after('<div class="modal_window" id="message"></div>');
	$('#message').html(message);
	$('#message').prepend('<a class="button bClose messageClose">x<a/>');
	$('#message').bPopup({
		closeClass : 'messageClose',
		modalClose : false,
		opacity : 0.6,
		modalColor : '#255',
		onClose : function() {
			$("#message").remove();
		}
	});
}

function validateItemForm(form) {
	var result = true;

	$('#errorMessage_name').remove();
	$('#errorMessage_price').remove();
	$('#errorMessage_quantity').remove();
	$('#errorMessage_desc').remove();
	if (form.itemName.value == '') {
		$('#itemName')
				.after(
						'<span class="small_error_message" id="errorMessage_name">*please enter name</span>');
		result = false;
	}
	var quantity = form.itemQuantity.value;
	if (!((quantity > 0) && (quantity < 2147483647))) {
		$('#itemQuantity')
				.after(
						'<span class="small_error_message" id="errorMessage_price">*quantity should be between 1 and 2147483646</span>');
		result = false;
	}
	var price = form.itemPrice.value;
	if (!((price > 0) && (price < 999999999))) {
		$('#itemPrice')
				.after(
						'<span class="small_error_message" id="errorMessage_quantity">*price should be between 0 and 999999999, and use dot to separate decimal and integer parts.</span>');
		result = false;
	}
	var description = form.itemDescription.value;
	if (description.length > 32672) {
		$('#itemDescription')
				.after(
						'<span class="small_error_message" id="errorMessage_desc">*max symbols - 32672</span>');
		result = false;
	}

	return result;
}
/*
 * ============================================================= Log in
 * =============================================================
 */

function authenticate() {
	$("#errorMessage").empty();
	jQuery.ajax({
		type : 'POST',
		datatype : 'json',
		url : ctPath + '/' + 'main',
		data : 'command=authenticate&' + $('#login_form').serialize(),
		success : function(data) {
			var dataObject = jQuery.parseJSON(data);
			// Redirect to page that we got
			if (dataObject.isValid) {
				console.log(dataObject.redirectUrl);
				window.location = dataObject.redirectUrl;
			} else {
				$("#errorMessage").html(dataObject.errorMessage);
			}
		},
		error : function(xhr, ajaxOptions, thrownError) {
			alert('Error: ' + xhr.status);
		}
	});
}

/*
 * ============================================================= Shopping cart
 * =============================================================
 */

function showShoppingCart() {
	jQuery.ajax({
		type : 'GET',
		datatype : 'html',
		url : ctPath + '/' + 'main',
		data : 'command=show_shopping_cart',
		success : function(data) {
			var $html = $(data);
			var $error_message = $("#errorMessage", $html);
			$('#main_container').after(
					'<div class="modal_window" id="cart_pop_up"></div>');

			if ($error_message.length == 0) {
				$('#cart_pop_up').html(data);
			} else {

				// we got error page, so show error message
				$('#cart_pop_up').html($error_message.get(0));
			}

			$('#cart_pop_up').prepend(
					'<a class="button bClose cartClose">x<a/>');

			$('#cart_pop_up').bPopup({
				closeClass : 'cartClose',
				modalClose : false,
				opacity : 0.6,
				modalColor : '#255',
				onClose : function() {
					$("#cart_pop_up").remove();
				}
			});
		},
		error : function(xhr, ajaxOptions, thrownError) {
			alert('Error: ' + xhr.status);
		}
	});
}

function closeShoppingCart() {
	$('#cart_pop_up').bPopup().close();
}

function addToCart() {
	jQuery
			.ajax({
				type : 'POST',
				datatype : 'json',
				url : ctPath + '/' + 'main',
				data : 'command=add_to_cart&' + $('#by_item_form').serialize(),
				success : function(data) {
					var $error_message;
					try {
						var $html = $(data);
						var $error_message = $("#errorMessage", $html);

						// we got error page, so show error message
						message = $error_message.get(0);
						showMessage(message);

					} catch (e) {

						// we got json answer
						var dataObject = jQuery.parseJSON(data);
						if (dataObject.isSuccessfullyAdded) {
							showShoppingCart();
						} else {
							var message = 'Can\'t add item to cart, please write administrator about this!';
							showmessage(message);
						}
					}
				},
				error : function(xhr, ajaxOptions, thrownError) {
					alert('Error: ' + xhr.status);
				}
			});
}

function closeMessage() {
	$('#message').bPopup().close();
}

function placeOrder() {
	jQuery
			.ajax({
				type : 'POST',
				datatype : 'json',
				url : ctPath + '/' + 'main',
				data : 'command=place_order',
				success : function(data) {
					var $error_message;
					try {
						var $html = $(data);
						var $error_message = $("#errorMessage", $html);

						// we got error page, so show error message
						message = $error_message.get(0);
						showMessage(message);

					} catch (e) {

						// we got json answer
						var dataObject = jQuery.parseJSON(data);
						if (dataObject.isOrderPlaced) {

							// So order placed, and we show it's id to customer.
							message = 'Order successfuly placed, it\'s id is '
									+ dataObject.orderId;
						} else {

							// Order isn't placed because of errors in cart's
							// data
							// or any
							// other problem except internal server error
							// Just show message about error
							message = 'Order wasn\'t placed due errors. Please check your cart for mistakes and contact administrator';
						}
						showMessage(message);
					}
				},
				error : function(xhr, ajaxOptions, thrownError) {
					alert('Error: ' + xhr.status);
				}
			});
}

function clearCart() {
	jQuery
			.ajax({
				type : 'GET',
				datatype : 'html',
				url : ctPath + '/' + 'main',
				data : 'command=clear_shopping_cart',
				success : function(data) {
					var $error_message;
					try {
						var $html = $(data);
						var $error_message = $("#errorMessage", $html);

						// we got error page, so show error message
						message = $error_message.get(0);
						showMessage(message);

					} catch (e) {

						// we got json answer
						var dataObject = jQuery.parseJSON(data);
						if (dataObject.isCleared) {
							closeShoppingCart();
							showShoppingCart();
						} else {
							var message = 'Can\'t empty cart, please write administrator about this!';
							showmessage(message);
						}
					}
				},
				error : function(xhr, ajaxOptions, thrownError) {
					alert('Error: ' + xhr.status);
				}
			});
}

/*
 * ============================================================= Orders list
 * =============================================================
 */

function showOrders() {
	jQuery.ajax({
		type : 'GET',
		datatype : 'html',
		url : ctPath + '/' + 'main',
		data : 'command=show_orders_list',
		success : function(data) {
			var $html = $(data);
			var $error_message = $("#errorMessage", $html);

			$('#main_container').after(
					'<div class="modal_window" id="orders_pop_up"></div>');

			console.log($error_message);

			if ($error_message.length == 0) {
				$('#orders_pop_up').html(data);
			} else {

				// we got error page, so show error message
				$('#orders_pop_up').html($error_message.get(0));
			}

			$('#orders_pop_up').prepend(
					'<a class="button bClose ordersClose">x<a/>');

			$('#orders_pop_up').bPopup({
				closeClass : 'ordersClose',
				modalClose : false,
				opacity : 0.6,
				modalColor : '#150',
				onClose : function() {
					$("#orders_pop_up").remove();
				}
			});
		},
		error : function(xhr, ajaxOptions, thrownError) {
			alert('Error: ' + xhr.status);
		}
	});
}

function closeOrders() {
	$('#orders_pop_up').bPopup().close();
}

function payForOrder(orderId) {
	jQuery
			.ajax({
				type : 'GET',
				datatype : 'html',
				url : ctPath + '/' + 'main',
				data : 'command=pay_for_order&orderId=' + orderId,
				success : function(data) {
					var $error_message;
					try {
						var $html = $(data);
						var $error_message = $("#error_message", $html);

						// we got error page, so show error message
						message = $error_message.get(0);
						showMessage(message);

					} catch (e) {

						// we got json answer
						var dataObject = jQuery.parseJSON(data);
						if (dataObject.isSuccessfulyPaid) {
							closeOrders();
							showOrders();
						} else {
							var message = 'Can\'t pay for order, please write administrator about this!';
							showmessage(message);
						}
					}
				},
				error : function(xhr, ajaxOptions, thrownError) {
					alert('Error: ' + xhr.status);
				}
			});
}